-- This file is part of the Fantasy Grounds Open Foundation Ruleset project. 
-- For the latest information, see http://www.fantasygrounds.com/
--
-- Copyright 2008 SmiteWorks Ltd.
--
-- This file is provided under the Open Game License version 1.0a
-- Refer to the license.html file for the full license text
--
-- All producers of work derived from this material are advised to
-- familiarize themselves with the license, and to take special
-- care in providing the definition of Product Identity (as specified
-- by the OGL) in their products.
--
-- All material submitted to the Open Foundation Ruleset project must
-- contain this notice in a manner applicable to the source file type.


local donotification = true;


function onInit()
	activewidget = addBitmapWidget(activeicon[1]);
	activewidget.setVisible(false);
	
	if getName() == "" or not window.getDatabaseNode() then
		print("Warning: Combat tracker entry with no activation data field");
		print(window.getClass());
		state = false;
	else
		statenode = window.getDatabaseNode().createChild(getName(), "number");
		statenode.onUpdate = stateUpdated;
		setState(statenode.getValue() ~= 0, true);
	end
end

-- Activity state
function setState(s, internal)
	state = s;
	if not internal and statenode then
		if state then
			statenode.setValue(1);
		else
			statenode.setValue(0);
		end
	end
	
	activewidget.setVisible(state);
	window.token.setActive(state);

	if window.activityChanged then
		window.activityChanged(state);
	end
end

function getState()
	return state;
end

function stateUpdated()
	setState(statenode.getValue() ~= 0, true);
end

-- Activation requests
function isActive()
	return getState();
end

function setActive(state)
	setState(state);
	
	if state and donotification then
		-- Turn notification
		local msg = {};
		msg.text = window.name.getValue();
		msg.font = "narratorfont";
		msg.icon = "indicator_flag";
		
		ChatManager.deliverMessage(msg);
		
		local usernode = window.link.getTargetDatabaseNode();
		if usernode then
			User.ringBell(usernode.getName());
		end
	end
end

-- Notification state
function setNotification(state)
	donotification = state;
end

-- UI events
function onClickDown(button, x, y)
	return true;
end

function onClickRelease(button, x, y)
	if not state then
		window.windowlist.requestActivation(window);
	end
end

function onDrag(button, x, y, draginfo)
	draginfo.setType("combattrackeractivation");
	draginfo.setIcon(activeicon[1]);

	activewidget.setVisible(false);

	return true;
end

function onDragEnd(draginfo)
	if state then
		activewidget.setVisible(true);
	end
end

function onDrop(x, y, draginfo)
	if draginfo.isType("combattrackeractivation") then
		window.getTracker().requestActivation(window);
	end
end



